<template>
	<div class="form-wrapper">
		<Form :label-width="80" ref="form" :model="formData" :rules="rules">
			<FormItem label="姓名" prop="name">
				<input v-model="formData['name']">
			</FormItem>
			<FormItem label="年龄">
				<input v-model="formData['age']">
			</FormItem>
			<FormItem>
				<Button type="primary" @click="handleSubmit()">Submit</Button>
			</FormItem>
		</Form>
	</div>

</template>

<script>
	import {sendFormData} from "../api/data";

	const validateName = (rule, value, callback) => {
		if (value !== 'Jack') {
			callback(new Error('The name is error'));
		} else {
			callback();
		}
	};

	export default {
		data() {
			return {
				formData: {
					name: '',
					age: 18
				},
				rules: {
					name: [
						{required: true, message: 'The name cannot be empty', trigger: 'blur'},
						{validator: validateName, trigger: 'blur'}
					]
				}
			}
		},
		methods: {
			handleSubmit() {
				this.$refs.form.validate(valid => {
					if (valid) {
						sendFormData(this.formData).then(res => {
							this.$Message.info(res.data);
						});
					}
				})
			}
		}
	}
</script>

<style lang="less">
	.form-wrapper {
		padding: 20px;
	}
</style>
